<template>
  <div class="home-container">
    <!-- pc -->
    <div class="PC">
      <div>
        <Head />
        <div class="main-content">
          <div class="side-menu">
            <div
              v-for="(item, index) in routerList"
              :key="item.id"
              @click="switchApp(item)"
              :class="['menu-item', selectIndex == item.id ? 'active' : '']"
            >
              <div class="menu-icon">
                <img :src="item.img" alt="" />
              </div>
              <div class="menu-text">
                {{ item.nameA }}
              </div>
            </div>
          </div>
          <div class="content-area">
            <!-- 主应用路由 -->
            <RouterView v-if="isMainAppRoute"></RouterView>
            <!-- 子应用容器 - 始终保持在DOM中，只是通过样式控制显示/隐藏 -->
            <div id="container"></div>
          </div>
        </div>
        
      </div>
    </div>

    <!-- 移动端 -->
    <div class="move">
      <Head />
      <div class="mobile-content">
        <!-- 主应用路由 -->
        <RouterView v-if="isMainAppRoute"></RouterView>
        <!-- 子应用容器 - 始终保持在DOM中，只是通过样式控制显示/隐藏 -->
        <div id="mobile-container"></div>
      </div>
      <div class="mobile-nav">
        <div
          v-for="item in mobileRouterList"
          :key="item.id"
          @click="switchApp(item)"
          :class="['mobile-nav-item', selectIndex == item.id ? 'active' : '']"
        >
          <div class="mobile-nav-icon">
            <img :src="item.img" alt="" />
          </div>
          <div class="mobile-nav-text">
            {{ item.name }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onBeforeMount, onMounted, nextTick, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import Head from "../../components/Head.vue";
import { RouterView } from "vue-router";
import { useCounterStore } from "@/stores/counter";
import { initGlobalState } from "qiankun";
import { isMobile } from "../../utils/mobile-adapter";

// 创建一个了全局状态池
const actions = initGlobalState({
  username: "zhangsan",
  userInfo: { name: "主应用用户", role: "admin" }, // 用户信息
  theme: "light", // 主题配置
  isLogin: true, // 登录状态
});
//注册监听器，vue3应用放在状态池中
actions.onGlobalStateChange((state, prev) => {
  console.log("新值", state);
  console.log("旧值", prev);
});
// 扩展Window接口
declare global {
  interface Window {
    checkContainer: () => boolean;
  }
}

const router = useRouter();
const route = useRoute();
const store = useCounterStore();

// 调试：获取当前用户信息
const userDataStr = localStorage.getItem('data');
if (userDataStr) {
  try {
    const userData = JSON.parse(userDataStr);
    console.log("Home组件中的用户数据:", JSON.stringify(userData));
    console.log("Home组件中的用户角色:", userData.department || '员工');
  } catch (e) {
    console.error("解析用户数据出错:", e);
  }
}

// 使用store中的路由列表，这样会随着用户权限动态变化
const routerList = computed(() => {
  console.log("当前路由列表:", JSON.stringify(store.routerList.map(r => ({
    id: r.id,
    name: r.nameA,
    router: r.router
  }))));
  return store.routerList;
});

// 移动端路由列表，限制显示数量，避免底部导航过于拥挤
const mobileRouterList = computed(() => {
  // 获取用户角色
  let userRole = '员工';
  if (userDataStr) {
    try {
      const userData = JSON.parse(userDataStr);
      userRole = userData.department || '员工';
    } catch (e) {
      console.error("解析用户数据出错:", e);
    }
  }
  
  // 根据用户角色决定显示的菜单项
  let maxItems = 7; // 移动端最多显示5个菜单项
  
  // 优先显示工作台和流程审批
  let priorityRoutes = routerList.value.filter(route => 
    route.router === '/work' || route.router === '/process'
  );
  
  // 根据角色添加其他重要菜单项
  if (userRole === 'CEO') {
    // CEO显示所有菜单，但限制数量
    return routerList.value.slice(0, maxItems);
  } else if (userRole === 'HR' || userRole === '人事') {
    // HR优先显示员工管理和部门管理
    const hrPriorities = routerList.value.filter(route => 
      route.router === '/staff' || route.router === '/organization'
    );
    return [...priorityRoutes, ...hrPriorities].slice(0, maxItems);
  } else if (userRole === '行政部' || userRole === 'ADMIN' || userRole === '行政') {
    // 行政优先显示行政管理、员工管理和部门管理
    const adminPriorities = routerList.value.filter(route => 
      route.router === '/administration' || route.router === '/staff' || route.router === '/organization'
    );
    return [...priorityRoutes, ...adminPriorities].slice(0, maxItems);
  } else {
    // 普通员工只显示工作台和流程审批
    return priorityRoutes;
  }
});

// 判断当前是否是主应用路由
const isMainAppRoute = computed(() => {
  // 子应用的路由前缀
  const microAppRoutes = ["/organization", "/staff", "/react", "/administration", "/finance", "/process"];
  return !microAppRoutes.some((prefix) => route.path.startsWith(prefix));
});

// 当前选中的菜单项
const selectIndex = ref(0);

// 确保容器元素已准备好
onMounted(() => {
  // 如果当前路径为根路径，重定向到work页面
  if (route.path === "/") {
    console.log("检测到根路径，重定向到work页面");
    router.push("/work");
  }

  // 根据当前路由设置选中的菜单项
  const obj = routerList.value.find((v) => v.router == route.path);
  if (obj) {
    selectIndex.value = obj.id;
  } else {
    // 如果是work路由，默认选中工作台
    if (route.path === "/work") {
      selectIndex.value = 0; // 工作台的ID
    }
  }

  console.log("Home组件已挂载");
  console.log("当前设备类型:", isMobile() ? "移动端" : "桌面端");
  console.log("当前路由:", route.path);

  // 创建全局方法，用于检查容器是否存在
  window.checkContainer = () => {
    const container = document.getElementById("container");
    const mobileContainer = document.getElementById("mobile-container");

    console.log("检查容器:", {
      container: container ? "存在" : "不存在",
      mobileContainer: mobileContainer ? "存在" : "不存在",
      isMobile: isMobile(),
    });

    if (container || mobileContainer) {
      return true;
    } else {
      console.error("容器元素不存在!");
      return false;
    }
  };

  // 确保容器元素准备好后通知主应用
  nextTick(() => {
    const container = document.getElementById("container");
    const mobileContainer = document.getElementById("mobile-container");

    console.log("容器元素准备状态:", {
      container: container ? "已准备" : "未准备",
      mobileContainer: mobileContainer ? "已准备" : "未准备",
    });

    if (container || mobileContainer) {
      console.log("容器元素已准备好");
      // 创建自定义事件通知容器已准备好
      window.dispatchEvent(new CustomEvent("container-ready"));
    }
  });
});

// 监听路由变化，确保子应用容器正确显示
watch(
  () => route.path,
  (newPath) => {
    console.log("路由变化:", newPath);

    // 检查是否是微应用路由
    const isMicroApp = [
      "/organization",
      "/staff",
      "/react",
      "/administration",
      "/finance",
      "/process",
    ].some((prefix) => newPath.startsWith(prefix));

    if (isMicroApp) {
      console.log("检测到微应用路由:", newPath);
      nextTick(() => {
        const containerSelector = isMobile() ? "#mobile-container" : "#container";
        const container = document.querySelector(containerSelector);

        console.log("微应用容器状态:", {
          selector: containerSelector,
          exists: container ? true : false,
          display: container ? (container as HTMLElement).style.display : "不存在",
        });

        if (container) {
          (container as HTMLElement).style.display = "block";
        }
      });
    } else {
      // 主应用路由，隐藏子应用容器
      nextTick(() => {
        const container = document.getElementById("container");
        const mobileContainer = document.getElementById("mobile-container");

        if (container) container.style.display = "none";
        if (mobileContainer) mobileContainer.style.display = "none";
      });
    }
  },
  { immediate: true } // 立即执行一次
);

interface SubApp {
  id: number;
  name: string;
  nameA: string;
  img: string;
  router: string;
  entry?: string;
  type?: string;
  title?: string;
}

// 切换应用
const switchApp = (app: SubApp) => {
  console.log("切换应用:", app);
  selectIndex.value = app.id;

  // 确保容器元素存在并可见
  nextTick(() => {
    const container = document.getElementById("container");
    const mobileContainer = document.getElementById("mobile-container");
    const isMobileView = isMobile();
    const targetContainer = isMobileView ? mobileContainer : container;

    console.log("切换应用容器状态:", {
      isMobile: isMobileView,
      container: container ? "存在" : "不存在",
      mobileContainer: mobileContainer ? "存在" : "不存在",
      targetContainer: targetContainer ? "存在" : "不存在",
    });

    if (targetContainer) {
      // 如果将要跳转到子应用，确保容器显示
      const isMicroApp =
        app.router &&
        ["/organization", "/staff", "/react", "/administration", "/finance", "/process"].some((prefix) =>
          app.router.startsWith(prefix)
        );

      if (isMicroApp) {
        targetContainer.style.display = "block";
        console.log(`准备加载子应用，确保容器可见: ${app.router}`);
      } else {
        // 主应用路由，隐藏子应用容器
        if (container) container.style.display = "none";
        if (mobileContainer) mobileContainer.style.display = "none";
      }
    }
  });

  // 通过路由跳转激活子应用
  if (app.router) {
    router.push(app.router);
    
    // 在移动端，滚动到顶部
    if (isMobile()) {
      window.scrollTo(0, 0);
    }
  }
};
</script>

<style scoped>
.home-container {
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.main-content {
  height: calc(100vh - 60px);
  display: flex;
  background-color: #f0f2f8;
}

.content-area {
  width: calc(100vw - 100px);
  height: calc(100vh - 100px);
  margin: 0 auto;
  background-color: #fff;
  border-radius: 20px;
  position: relative;
  padding: 20px;
  box-sizing: border-box;
  overflow: hidden;
}

/* 确保子应用容器正确显示 */
#container,
#mobile-container {
  width: 100%;
  height: 100%;
  overflow: auto;
}

/* 移动端样式 */
.move {
  display: none;
  flex-direction: column;
  height: 100vh;
}

.mobile-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  padding-bottom: 70px; /* 为底部导航留出空间 */
  background-color: #f0f2f8;
  position: relative;
}

.mobile-nav {
  display: flex;
  justify-content: space-around;
  background-color: #fff;
  padding: 8px 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 100;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
}

.mobile-nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 5px 0;
  border-radius: 10px;
  flex: 1;
  max-width: 60px;
  min-width: 50px;
}

.mobile-nav-icon {
  display: flex;
  justify-content: center;
  align-items: center;
}

.mobile-nav-icon img {
  width: 25px;
  height: 25px;
}

.mobile-nav-text {
  font-size: 12px;
  margin-top: 4px;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  padding: 0 2px;
}

@media (max-width: 1000px) {
  .PC {
    display: none;
  }
  .move {
    display: flex;
  }

  /* 确保移动端子应用容器占满可用空间 */
  #mobile-container {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    padding: 10px;
    box-sizing: border-box;
    background-color: #fff;
  }
}

@media (min-width: 1000px) {
  .PC {
    display: block;
  }
  .move {
    display: none;
  }
}

.active {
  color: #263961;
  background-color: rgba(38, 57, 97, 0.1);
}

.side-menu {
  width: 85px;
  height: 100%;
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  overflow-y: auto;
  padding-top: 10px;
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 80px;
  width: 70px;
  margin: 8px auto;
  border-radius: 12px;
  cursor: pointer;
  position: relative;
}

.menu-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 10px;
  margin-bottom: 6px;
  background-color: #f5f7fa;
}

.menu-item.active .menu-icon {
  background-color: rgba(38, 57, 97, 0.1);
  animation: iconPulse 0.5s ease;
}

.menu-icon img {
  width: 24px;
  height: 24px;
}

.menu-text {
  font-size: 12px;
  text-align: center;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 0 5px;
  box-sizing: border-box;
}

.menu-item.active .menu-text {
  font-weight: 500;
}

/* 只在切换时添加动画 */
@keyframes iconPulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

/* 菜单项切换动画 */
.menu-item.active {
  animation: menuActivate 0.3s ease forwards;
}

@keyframes menuActivate {
  0% {
    background-color: transparent;
  }
  100% {
    background-color: rgba(38, 57, 97, 0.1);
  }
}

/* 移动端适配的额外样式 */
@media (max-width: 768px) {
  .mobile-content {
    padding: 8px;
  }

  .mobile-nav-item {
    width: 50px;
  }

  .mobile-nav-icon img {
    width: 22px;
    height: 22px;
  }

  .mobile-nav-text {
    font-size: 11px;
  }

  #mobile-container {
    padding: 8px;
  }
}

@media (max-width: 480px) {
  .mobile-content {
    padding: 5px;
  }

  .mobile-nav-item {
    width: 45px;
  }

  .mobile-nav-icon img {
    width: 20px;
    height: 20px;
  }

  .mobile-nav-text {
    font-size: 10px;
  }

  #mobile-container {
    padding: 5px;
  }
}
</style>
